package com.deman.framework.rpc.netty;

import com.deman.framework.rpc.core.MessageCallBack;
import com.deman.framework.rpc.core.MessageCallBackHolder;
import com.deman.framework.rpc.model.MessageResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClientHandler extends ChannelInboundHandlerAdapter {
    Logger logger = LoggerFactory.getLogger(ClientHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.debug("{}", msg);
        if (msg instanceof MessageResponse) {
            MessageResponse messageResponse = (MessageResponse) msg;
            logger.debug("{}", messageResponse.getMessageId());
            try {
                MessageCallBack messageCallBack = MessageCallBackHolder.get(messageResponse.getMessageId());
                messageCallBack.over(messageResponse);
            }catch (Exception e){
                logger.error("messageId:[{}],error:[{}]",messageResponse.getMessageId(),e.getMessage(),e);
            }
        }else {
            ctx.fireChannelRead(msg);
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        ctx.fireExceptionCaught(cause);
    }
}
